﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Text;
using System.Data;

namespace Catering.Catering_Page.ShanShiFenXi
{
    public partial class yysfx : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SearchDate.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM'})");
            }
        }

        protected void lbtnTyleChar_Click(object sender, EventArgs e)
        {
            string strclassid = DDLTool1.GetDDL_Class();
            DateTime searchmonth = GetDateTime();
            if (searchmonth <= DateTime.MinValue)
            {
                View_Operaction_Common.Show(this, "请选年月！");
                return;
            }
            string starttime = "";
            string endtime = "";
            string week = this.dr_select_Week.SelectedValue;
            string[] splitweek = week.Split('|');
            if (splitweek.Length == 2)
            {
                starttime = splitweek[0];
                endtime = splitweek[1];
            }
            if (strclassid == "-10")
            {
                View_Operaction_Common.Show(this, "请选择班组！");
                return;
            }
            if (week == "")
            {
                View_Operaction_Common.Show(this, "请选周期！");
                return;
            }
            decimal[] al_sheruliang = new decimal[24];
            Dictionary<string, decimal> al_shijizhi = new Dictionary<string, decimal>();
            string tojiname = "[";
            int groupid = 0;
            int rid = 0;
            DataTable dt = new Catering_Rules.T_Recipes().GetRecipesByInfo(strclassid, starttime, endtime).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                groupid = Convert.ToInt32(dt.Rows[0]["GroupID"]);
                rid = Convert.ToInt32(dt.Rows[0]["id"]);// 食谱id                
            }
            dt.Dispose();
            al_shijizhi = ShiJIzhi(strclassid,rid.ToString(), week);
            al_sheruliang = LoadSRliang(groupid);

            string str = "";
            if (al_shijizhi != null)
            {
                StringBuilder Sresult = new StringBuilder("");
                Sresult.Append("{");
                Sresult.Append("name:'实际值/目标值',");
                Sresult.Append("data: [");
                string StrData = "";
                int j = 0;
                foreach (string key in al_shijizhi.Keys)
                {
                    decimal shiji = al_shijizhi[key];//实际值
                    decimal biaozhun = al_sheruliang[j];
                    decimal value = 0;
                    if (biaozhun > 0) value = shiji / biaozhun * 100;
                    StrData += value.ToString("0.00") + ",";
                    tojiname += "'" + key + "',";
                    j++;
                }
                StrData = StrData.Length > 0 ? StrData.Substring(0, StrData.Length - 1) : "";
                tojiname = tojiname.Length > 0 ? tojiname.Substring(0, tojiname.Length - 1) : "";
                tojiname += "]";
                Sresult.Append(StrData + "]");
                Sresult.Append("},");
                str = Sresult.ToString();
            }
            str = str.Length > 0 ? str.Substring(0, str.Length - 1) : "";

            ClientScript.RegisterStartupScript(ClientScript.GetType(), "myScript", "GetDataGroup(" + tojiname + ",'" + Title + "'," + str + ");", true);
        }

        protected void SearchDate_TextChanged(object sender, EventArgs e)
        {
            DateTime dtime = GetDateTime();
            if (dtime != null && dtime > DateTime.MinValue)
            {
                this.LoadZouDrop(dtime.Year, dtime.Month);
            }
        }

        public DateTime GetDateTime()
        {
            DateTime dtime = DateTime.MinValue;
            string strDate = this.SearchDate.Text.Trim();
            if (!string.IsNullOrEmpty(strDate)) DateTime.TryParse(strDate, out dtime);
            return dtime;
        }

        //计算周期
        public void LoadZouDrop(int y, int M)
        {
            this.dr_select_Week.Items.Clear();
            //每月天数数组
            int[] daysMonth = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            daysMonth[1] = (0 == y % 4 && (y % 100 != 0 || y % 400 == 0)) ? 29 : 28;

            //总天数
            int daycount = daysMonth[M - 1];

            //得到1号对应的星期
            string strDatetime = y.ToString() + "-" + M.ToString() + "-01";
            int w = this.GetWeekInt(Convert.ToDateTime(strDatetime).DayOfWeek);

            int bctianshu = 0;//要想填充一个完整的table  需要补充的天数

            if (w == 1)
            {//判断1号是否是星期一
                if ((daycount % 7) == 0)
                {//判断是否能被星期整除
                    int zhouCount = daycount / 7;
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + (i * 7).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                }
                else
                {
                    int zhouCount = daycount / 7;
                    bctianshu = 7 - (daycount % 7); //需要补充的天数
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + (i * 7).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                    ListItem ite = new ListItem();
                    ite.Text = "第" + (zhouCount + 1).ToString() + "周";
                    if (M != 12)
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + 1).ToString() + "|" + y.ToString() + "-" + (M + 1).ToString() + "-" + bctianshu.ToString();
                    }
                    else
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + 1).ToString() + "|" + (y + 1).ToString() + "-" + "01" + "-" + bctianshu.ToString();
                    }
                    this.dr_select_Week.Items.Add(ite);
                }
            }
            else
            {
                int dygxingqiyi = ((w == 0) ? 1 : (8 - w)); //距离下一个星期一还有几天
                if (((daycount - dygxingqiyi) % 7) == 0)
                {
                    int zhouCount = (daycount - dygxingqiyi) / 7;
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + dygxingqiyi + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + ((i * 7) + dygxingqiyi).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                }
                else
                {
                    bctianshu = 7 - ((daycount - dygxingqiyi) % 7); //需要补充的天数
                    int zhouCount = (daycount - dygxingqiyi) / 7;
                    for (int i = 1; i <= zhouCount; i++)
                    {
                        ListItem item = new ListItem();
                        item.Text = "第" + i.ToString() + "周";
                        item.Value = y.ToString() + "-" + M.ToString() + "-" + (((i - 1) * 7) + dygxingqiyi + 1).ToString() + "|" + y.ToString() + "-" + M.ToString() + "-" + ((i * 7) + dygxingqiyi).ToString();
                        this.dr_select_Week.Items.Add(item);
                    }
                    ListItem ite = new ListItem();
                    ite.Text = "第" + (zhouCount + 1).ToString() + "周";
                    if (M != 12)
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + dygxingqiyi + 1).ToString() + "|" + y.ToString() + "-" + (M + 1).ToString() + "-" + bctianshu.ToString();
                    }
                    else
                    {
                        ite.Value = y.ToString() + "-" + M.ToString() + "-" + ((zhouCount * 7) + dygxingqiyi + 1).ToString() + "|" + (y + 1).ToString() + "-" + "01" + "-" + bctianshu.ToString();
                    }
                    this.dr_select_Week.Items.Add(ite);

                }
            }
        }

        //获取周对应的值
        public int GetWeekInt(DayOfWeek week)
        {
            switch (week)
            {
                case DayOfWeek.Monday://星期一
                    return 1;
                    break;
                case DayOfWeek.Tuesday://星期二
                    return 2;
                    break;
                case DayOfWeek.Wednesday://星期三
                    return 3;
                    break;
                case DayOfWeek.Thursday://星期四
                    return 4;
                    break;
                case DayOfWeek.Friday://星期五
                    return 5;
                    break;
                case DayOfWeek.Saturday://星期六
                    return 6;
                    break;
                case DayOfWeek.Sunday://星期日
                    return 0;
                    break;
                default:
                    return -1;
                    break;
            }
        }

        //加载标准摄入量总和
        public decimal[] LoadSRliang(int groupid)
        {
            decimal[] al_sheruliang = new decimal[24];
            decimal[] bl_Num = new decimal[24]; //存放最后的标量值

            StringBuilder sb = new StringBuilder();//标量值查询条件
            sb.Append("1=2");
            DataTable dt_CateringGroupInfo = new DataTable();
            dt_CateringGroupInfo = new Catering_Rules.CateringGroupInfo().GetNETypes(groupid).Tables[0];
            if (dt_CateringGroupInfo != null && dt_CateringGroupInfo.Rows.Count > 0)
            {
                foreach (DataRow row in dt_CateringGroupInfo.Rows)
                {
                    string Group_tedianId = row["Group_tedianID"].ToString(); //适合人群
                    string SexId = row["SexID"].ToString();//性别
                    string AgeId = row["OldAreaID"].ToString();//年龄段
                    string LaborGradeId = row["LaborGradeID"].ToString();//劳动级别
                    string strwhere = "SexID=" + SexId + " and OldAreaID=" + AgeId + " and LaborGradeID=" + LaborGradeId + " and Group_tedianID=" + Group_tedianId;
                    sb.Append(" or (" + strwhere + ")");
                }

                //计算标量值
                DataTable dt_Ingestion = new Catering_Rules.Ingestion().GetList(sb.ToString()).Tables[0];
                foreach (DataRow row in dt_Ingestion.Rows)
                {
                    bl_Num[Convert.ToInt32(row["NutritionElementsID"]) - 1] += Convert.ToDecimal(row["Number"]);
                }

                for (int i = 0; i < 24; i++)
                {
                    al_sheruliang[i] = (Convert.ToDecimal(bl_Num[i]) / Convert.ToDecimal(dt_CateringGroupInfo.Rows.Count));
                }
            }
            return al_sheruliang;
        }

        public Dictionary<string, decimal> ShiJIzhi(string Strclassid,string Rid, string week)
        {
            Dictionary<string, decimal> al_shijizhi = new Dictionary<string, decimal>();
            string[] splitweek = week.Split('|');
            int id = 0;
            int classid = 0;
            DateTime startTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            Int32.TryParse(Rid, out id);
            Int32.TryParse(Strclassid, out classid);
            DateTime.TryParse(splitweek[0], out startTime);
            DateTime.TryParse(splitweek[1], out endTime);

            //DataTable dt = new Catering_Rules.NutrientComposition().GetNutritionElements(id, startTime, endTime).Tables[0];
            DataTable dt = new Catering_Rules.NutrientComposition().GetNutritionElementsByFromRecords(classid, startTime, endTime).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string Elements = dt.Rows[i]["Elements"].ToString();
                    int nutritionid = Convert.ToInt32(dt.Rows[i]["NutritionElementsID"]);
                    decimal content = Convert.ToDecimal(dt.Rows[i]["Numbers"]);
                    //decimal weekNum = Convert.ToDecimal(dt.Rows[i]["CountWeek"]);
                    //al_shijizhi.Add(Elements, (content / weekNum));
                    al_shijizhi.Add(Elements, content);
                }
            }
            return al_shijizhi;
        }
    }
}